<template>
  <van-tabbar
      v-model="active"
      @change="onChange"
      :active-color="activeColor"
      :inactive-color="inactiveColor"
      class="px-w100 tab-bar-container">
    <van-tabbar-item :key="`tab-bar-item-${i}`" v-for="(item,i) of lists">
      <span>{{ item.title }}</span>
      <template #icon="props">
        <img class="tab-bar-icon" alt="" :src="props.active ? item.iconActive : item.icon"/>
      </template>
    </van-tabbar-item>
  </van-tabbar>
</template>

<script lang="ts">
import {defineComponent} from "vue";


export default defineComponent({
  name: "TabBar",
  props: {
    activeColor: {
      type: String,
      default: '#FB5848',
    },
    inactiveColor: {
      type: String,
      default: '#292D38',
    },
  },
  data() {
    return {
      active: 0,
      lists: [
        {
          title: '首页',
          routeName: 'home',
          icon: require('../../assets/images/tabbar/home_inactive.png'),
          iconActive: require('../../assets/images/tabbar/home_active.png'),
        },
        {
          title: '购物车',
          routeName: 'cart',
          icon: require('../../assets/images/tabbar/cart_inactive.png'),
          iconActive: require('../../assets/images/tabbar/cart_active.png'),
        },
        {
          title: '我的',
          routeName: 'profile',
          icon: require('../../assets/images/tabbar/profile_inactive.png'),
          iconActive: require('../../assets/images/tabbar/profile_active.png'),
        },
      ]
    }
  },
  watch: {
    '$route'({path}) {
      // 保证刷新后导航栏高亮项目正确
      const lists = this.lists
      if (path === '/') {
        this.active = 0;
      }
      for (let i in lists) {
        const index = path.indexOf('/' + lists[i].routeName)
        if (index === 0) {
          this.active = Number(i);
          break;
        }
      }
    }
  },
  methods: {
    onChange(index: number) {
      const {routeName} = this.lists[index]
      if (routeName) {
        this.$router.push({name: routeName})
      }
    }
  }
})
</script>
<style lang="less" scoped>
.tab-bar-container {
  height: 60px;

  .tab-bar-icon {
    width: 25px;
    height: 25px;
  }
}
</style>

